package controller;

import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.DevUser;
import pojo.User;
import service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Dell on 2019/1/12.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

   @RequestMapping("/login")
   public String toIndex(User user, HttpServletRequest request, Model model){
       return "index";
   }

    @RequestMapping("/login.html")
    public String toLogin(){
       return "login";
   }

    @RequestMapping("/register")
    public String registerIndex(User user, HttpServletRequest request, Model model){
        userService.addUserInfo(user);
         return "login";
    }

    @RequestMapping("/register.html")
    public String toRegister(){
        return "register";
    }


    @RequestMapping("/devLogin")
    @ResponseBody
    public Object loginMain(DevUser devUser, HttpServletRequest req){
        if(req.getSession().getAttribute("devuser")!=null){
            req.getSession().removeAttribute("devuser");
        }
        if(req.getSession().getAttribute("backuser")!=null){
            req.getSession().removeAttribute("backuser");
        }
        System.out.println("user---"+devUser.getDevCode());

        DevUser loginDevUser=userService.loginDev(devUser);

        String str="";
        if(loginDevUser!=null){
            req.getSession().setAttribute("devuser",loginDevUser);
            loginDevUser.setNum(2);
            str="ok";
        }else{
            str="err";
        }

        return JSONArray.toJSONString(str);
    }





    @RequestMapping("/backLogin")
    @ResponseBody
    public Object loginMains(User user, HttpServletRequest req){
        if(req.getSession().getAttribute("backuser")!=null){
            req.getSession().removeAttribute("backuser");
        }
        if(req.getSession().getAttribute("devuser")!=null){
            req.getSession().removeAttribute("devuser");
        }
        System.out.println("user---"+user.getUserCode()+"--"+user.getUserPassword());
        User loginUser=userService.loginBack(user);
        System.out.println(loginUser);
        String str="";
        if(loginUser!=null&&loginUser.getUserType()==1){
            req.getSession().setAttribute("backuser",loginUser);
            loginUser.setNum(1);
            str="ok";
        }else if(loginUser!=null&&loginUser.getUserType()!=1){
            str="noadmin";
        }else if(loginUser==null){
            str="err";
        }
        return JSONArray.toJSONString(str);
    }


    @RequestMapping("welcome.html")
    public String goWelcome(){
        return "welcome";
    }
}
